<template>
  <div>
    <el-form :model="formData" :rules="formDataRules" ref="formData">
      <h2>{{ $t("register.title") }}</h2>
      <el-form-item label="" prop="name" class="margin-top-2">
        <el-input
          class="border-bottom"
          prefix-icon="iconfont icongerenxinxi"
          v-model="formData.name"
          :placeholder="$t('public.placeholder.name')"
          maxlength="5"
        ></el-input>
      </el-form-item>
      <el-form-item label="" prop="telephone" class="margin-top-2">
        <el-input
          class="border-bottom"
          prefix-icon="iconfont iconxiugaishoujihaoma-01"
          v-model="formData.telephone"
          :placeholder="$t('public.placeholder.telephone')"
          maxlength="11"
        ></el-input>
      </el-form-item>
      <el-form-item label="" prop="verifyCode" class="margin-top-2">
        <el-input
          class="border-bottom"
          :placeholder="$t('public.placeholder.verifyCode')"
          prefix-icon="iconfont iconanquanxinxi"
          v-model="formData.verifyCode"
          maxlength="6"
        ></el-input>
        <el-link
          :underline="false"
          type="primary"
          class="btn-getSMS"
          @click="getSMS"
          :disabled="getSmsDisabled"
          >{{ btnText.getSMS }}</el-link
        >
      </el-form-item>
      <el-row class="margin-top">
        <el-checkbox v-model="readed"></el-checkbox>
        &nbsp;
        <span class="subtitle">{{ $t("register.read.part1") }}</span>
        <el-link
          type="primary"
          @click="
            dialogType = 'protocol';
            dialogVisible = true;
          "
          >{{ $t("register.read.part2") }}</el-link
        >
        <span class="subtitle">{{ $t("register.read.part3") }}</span>
        <el-link
          type="primary"
          @click="
            dialogType = 'privacy';
            dialogVisible = true;
          "
          >{{ $t("register.read.part4") }}</el-link
        >
      </el-row>
      <el-form-item class="margin-top-2">
        <el-button
          type="primary"
          class="form-control"
          :disabled="unallowed"
          @click="submitForm('formData')"
          >{{ $t("public.register") }}</el-button
        >
      </el-form-item>
    </el-form>
    <el-dialog
      title=""
      :visible.sync="dialogVisible"
      width="720px"
      :show-close="dialogShowClose"
      :close-on-click-modal="dialogCloseOnClickModal"
      :close-on-press-escape="dialogCloseOnPressEscape"
      center
      @open="openDialogProtocol"
      @close="closeDialogProtocol"
    >
      <div v-html="dialogContent"></div>
      <span slot="footer" class="dialog-footer align-center">
        <el-button
          size="small"
          type="primary"
          @click="dialogVisible = false"
          :disabled="dialogProtocol.closeDisabled"
          >{{ dialogProtocol.btnClose }}</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRichText,
  getSms,
  toRegister,
  toVerifyGraph,
  loginSuccess,
} from "../../api/login";

export default {
  name: "Register",
  props: {
    loading: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    unallowed() {
      return !this.readed;
    },
  },
  data() {
    var validateName = (rule, value, callback) => {
      let myreg = /^[\u4e00-\u9fa5]{2,5}$/;
      if (!myreg.test(value)) {
        callback(new Error(this.$t("public.error.name")));
      }
      callback();
    };
    var validatePhone = (rule, value, callback) => {
      let myreg = /^[1][0-9]{10}$/;
      if (!myreg.test(value)) {
        callback(new Error(this.$t("public.error.telephone")));
      }
      callback();
    };
    return {
      readed: false,
      dialogType: null,
      dialogContent: "",
      dialogVisible: false,
      dialogShowClose: false,
      dialogCloseOnClickModal: false,
      dialogCloseOnPressEscape: false,
      getSmsDisabled: false,
      btnText: {
        getSMS: this.$t("public.getSMS"),
      },
      formData: {
        name: "",
        telephone: "",
        verifyCode: "",
        language: this.$i18n.locale,
      },
      formDataRules: {
        name: [{ validator: validateName, trigger: "blur" }],
        telephone: [{ validator: validatePhone, trigger: "blur" }],
        verifyCode: [
          {
            required: true,
            message: this.$t("public.error.verifyCode"),
            trigger: "blur",
          },
        ],
      },
      dialogProtocol: {
        btnClose: "",
        closeDisabled: true,
      },
    };
  },
  watch: {
    dialogType: {
      handler(val) {
        this.dialogContent = "";
        let type = 0;
        if (val === "protocol") {
          type = 1;
        } else if (val === "privacy") {
          type = 2;
        }
        getRichText({ type: type }).then((res) => {
          this.dialogContent = res.data;
        });
      },
    },
  },
  created() {
    if (window.TencentCaptcha === undefined) {
      let script = document.createElement("script");
      let head = document.getElementsByTagName("head")[0];
      script.type = "text/javascript";
      script.charset = "UTF-8";
      script.src = "https://ssl.captcha.qq.com/TCaptcha.js";
      head.appendChild(script);
    }
  },
  methods: {
    startLoading() {
      this.$emit("loadingChange", true);
    },
    endLoading() {
      this.$emit("loadingChange", false);
    },
    getSMS() {
      let _this = this;
      _this.$refs["formData"].validateField("telephone", (error) => {
        if (error.length == 0) {
          var captcha = new TencentCaptcha("2082855902", function (res) {
            if (res.ret === 0) {
              // 防水墙验证前端成功
              toVerifyGraph({
                // ipAddr: "string",
                randstr: res.randstr,
                ticket: res.ticket,
              }).then((res) => {
                if (res.status === 200) {
                  getSms({
                    telephone: _this.formData.telephone,
                    smsType: "REGISTER",
                  }).then((res) => {
                    if (res.status === 200) {
                      _this.$message.success(
                        _this.errorCode[_this.$i18n.locale][res.message]
                      );
                      let s = 59,
                        text = _this.$t("public.text");
                      _this.btnText.getSMS = `${s} ${text}`;
                      let timer = setInterval(function () {
                        s--;
                        if (s <= 0) {
                          clearInterval(timer);
                          _this.btnText.getSMS = _this.$t("public.getSMS");
                          _this.getSmsDisabled = false;
                        } else {
                          _this.btnText.getSMS = `${s} ${text}`;
                          _this.getSmsDisabled = true;
                        }
                      }, 1000);
                    } else {
                      _this.$message.error(
                        _this.errorCode[_this.$i18n.locale][res.message]
                      );
                    }
                  });
                } else {
                  _this.$message.error(
                    _this.errorCode[_this.$i18n.locale][res.message]
                  );
                }
              });
            }
          });
          captcha.show(); // 启动防水墙
        } else {
          this.$message({
            message: this.$t("public.error.telephone"),
            type: "warning",
          });
          return false;
        }
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          toRegister({
            telephone: this.formData.telephone,
            isAgree: 2,
            name: this.formData.name,
            openid: "",
            verifyCode: this.formData.verifyCode,
          }).then((res) => {
            // this.$message({
            //   message: res.message,
            //   type: "success",
            // });
            // this.$alert(res.message, "", {
            //   confirmButtonText: this.$t("public.toLogin"),
            //   callback: () => {
            //     this.$emit("toChangePageType", "Login");
            //   },
            // });
            if (res.status === 200) {
              loginSuccess(res.data);
            } else {
              this.$message.error(
                this.errorCode[this.$i18n.locale][res.message]
              );
            }
          });
        } else {
          return false;
        }
      });
    },
    openDialogProtocol() {
      let s = 9,
        _this = this,
        text = "s";
      _this.dialogProtocol.btnClose = `${s} ${text}`;
      let timer = setInterval(function () {
        s--;
        if (s <= 0) {
          clearInterval(timer);
          _this.dialogProtocol.btnClose = _this.$t("public.close");
          _this.dialogProtocol.closeDisabled = false;
        } else {
          _this.dialogProtocol.btnClose = `${s} ${text}`;
        }
      }, 1000);
    },
    closeDialogProtocol() {
      this.dialogProtocol.closeDisabled = true;
    },
  },
};
</script>